package ibase.solr.servlet;



import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.CoreAdminParams;
import org.apache.solr.common.params.CoreAdminParams.CoreAdminAction;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.request.QueryResponseWriter;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrQueryResponse;


/**
 * Servlet implementation class SearchServlet
 */
public class SearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	//private static final String myServer = CommonConstants.TOMCAT_HOME +File.separator+"solr"+File.separator+"changecontrol";
	private static final String myServer = "http://localhost:9090/solr";
	private static final String solrHomeRelativePath = "D:"+File.separator+"Ashish"+File.separator+"apache-tomcat-6.0.41"+File.separator+"webapps"+File.separator+"solr";
	private static final String myCollection = "test";
	private static final String facet = "on";
	private static final int nbDocuments = 10;
	int start =0; 
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    // TODO Auto-generated method stub
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		try {
			
			String query = request.getParameter("SearchValue");
			//String coreName= request.getParameter("coreName");
			//String coreName= "changecontrol";
			CommonsHttpSolrServer server = new CommonsHttpSolrServer(myServer);
			server.setParser(new XMLResponseParser());
			SolrQuery solrQuery = new SolrQuery();
			solrQuery.setQuery(query);
			/*solrQuery.set("collectionName", myCollection);
			solrQuery.set("username", "qms");
			solrQuery.set("password", "qms");
			solrQuery.set("facet", facet);
			solrQuery.set("wt","xslt");
			solrQuery.setParam(CoreAdminParams. "rt","example.xsl");*/
			//solrQuery.setParam(CommonParams.QT, "/admin/cores");
			//solrQuery.setParam(CoreAdminParams.ACTION, CoreAdminParams.CoreAdminAction.CREATE.name());
			//solrQuery.setParam(CoreAdminParams.NAME,coreName);
			//solrQuery.setParam(CoreAdminParams.INSTANCE_DIR,"./" + coreName);
			//solrQuery.setParam(CoreAdminParams.CONFIG,solrHomeRelativePath + solrConfigHomeRelativePath);
			//solrQuery.setParam(CoreAdminParams.SCHEMA,solrHomeRelativePath + solrSchemaHomeRelativePath);
			solrQuery.setRows(nbDocuments);
			solrQuery.addFacetField("SCATNAME");
			//solrQuery.addFacetField("NFORMCATEGORYID"); 
			/*if(facetQuery != null)
			{
				solrQuery.addFacetQuery(facetQuery);
			}*/
			
			Map parameterMap = request.getParameterMap();
			System.out.println("parameterMap: ["+parameterMap.toString()+" ]");
			Set keySet = parameterMap.keySet();
			Iterator parameterMapIterator = keySet.iterator();
			while(parameterMapIterator.hasNext()) 
			{
				String key = (String)parameterMapIterator.next();
				String[] values = (String[])parameterMap.get(key);
				if("pageNo".equalsIgnoreCase(key))
				{
					for(int i = 0; i < values.length; i++) 
					{
						int pageNo = Integer.parseInt(values[i]);
						start= pageNo*nbDocuments;
					}
				}
				if(!("SearchValue".equalsIgnoreCase(key) || "pageNo".equalsIgnoreCase(key)))
				{
					for(int i = 0; i < values.length; i++) 
					{
						solrQuery.addFilterQuery(key + ":" + values[i]);
					}
				}	
			}
			solrQuery.setStart(start);
			System.out.println("solrQuery :[ "+solrQuery.toString()+" ]");
			QueryResponse rsp =server.query(solrQuery);
			System.out.println("@@@ rsp : [ "+rsp+" ]");
			//return server.query(solrParams);
			System.out.println("rsp: [ "+rsp.toString()+" ]");
			//System.out.println("@@@@ request.getRequestURI() :"+request.getRequestURI());
			//System.out.println("@@@@ request.getQueryString() :"+request.getQueryString());
			//System.out.println("@@@@ rsp : [" +rsp.getFacetFields().toString() + " ]");
			HttpSession session = request.getSession();
			session.setAttribute("solrResponse",rsp);
			session.setAttribute("requestUri", request.getRequestURI());
			session.setAttribute("queryString", request.getQueryString());
			RequestDispatcher reqDispatcher = request.getRequestDispatcher("/SearchDetail.jsp");
			reqDispatcher.forward(request, response);
			
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("Exception : [ "+e.getMessage() + " ]");
			e.printStackTrace();
			
		}
	}

}
